import {Injectable, Inject, forwardRef} from '@angular/core';
import {WECHAT_SHARE_CONFIG, WechatShareModule} from "./wechat-share.module";
import {Observable} from 'rxjs/Observable';
import {WechatShareConfig, WechatShareInterface} from "../../interface/wechat-share/wechat-share.model";


@Injectable()
export class WechatShareService {
  constructor(
    @Inject(forwardRef(() => WECHAT_SHARE_CONFIG)) private _wechatShareConfig: WechatShareConfig,
  ) {

  }

  public insertWechatJsSdk(): Observable<any> {

    return Observable.create((observer) => {
      const sdk = document.createElement("script"),
        target = document.getElementsByTagName("script")[0];
      sdk.id = 'seed-wechat-js';
      sdk.src = this._wechatShareConfig.jsSrc;
      target.parentNode.insertBefore(sdk, target);
      sdk.onload = () => {
        observer.next(true);
        observer.complete();
        this._createShareElement();
      };
      sdk.onerror = () => {
        observer.onerror(null);
      };
    });
  }

  public config(config: WechatShareConfig) {
    wx.config({
      debug: this._wechatShareConfig.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数
      appId: config.appId, // 必填，公众号的唯一标识
      timestamp: config.timestamp, // 必填，生成签名的时间戳
      nonceStr: config.nonceStr, // 必填，生成签名的随机串
      signature: config.signature, // 必填。注意，signature应由后台返回
      jsApiList: this._wechatShareConfig.jsApiList
    });
    return this;
  }

  private _createShareElement() {
    const title = document.createElement('div');
    title.id = 'seed-share-title';
    // const elements = ['seed-share-title', 'seed-share-desc', 'seed-share-imgUrl'];
    const elements = {
      title: 'seed-share-title',
      desc: 'seed-share-desc',
      imgUrl: 'seed-share-imgUrl'
    };

    for (const i in elements) {
      const target = document.getElementById(elements[i]);
      if (target) {
        return;
      } else {
        const node = document.createElement('input');
        node.type = 'hidden';
        node.id = elements[i];
        node.value = this._wechatShareConfig.defaults[i];
        document.body.appendChild(node);
      }
    }
    /* elements.forEach((v, i) => {
         const node = document.getElementById(v);
         if (node) {
             return;
         } else {
             const element = document.createElement('input');
             element.type = 'hidden';
             element.id = v;
             document.body.appendChild(element);
         }
     });*/
    return this;
  }

  fetchShareData(): WechatShareInterface {
   //  console.log(this.shareImgUrl)
    return {
      title: this.shareTitle,
      desc: this.shareDesc,
      imgUrl: this.shareImgUrl
    };
  }

  updateShareData(options: WechatShareInterface = {}) {
    // console.log(options.imgUrl || 'sfdsd');
    try {
      (<HTMLInputElement>document.getElementById('seed-share-title')).value = options.title || '';
      (<HTMLInputElement>document.getElementById('seed-share-desc')).value = options.desc || '';
      (<HTMLInputElement>document.getElementById('seed-share-imgUrl')).value = options.imgUrl || '';
    } catch (e) {
      console.warn(e);
    }

    return this;
  }


  private get shareTitle() {
    const title = (<HTMLInputElement>document.getElementById('seed-share-title')).value;
    if (title) {
      return title;
    }

    if (document.title) {
      return document.title;
    }

    return this._wechatShareConfig.defaults.title;
  }

  private get shareDesc() {
    const desc = (<HTMLInputElement>document.getElementById('seed-share-desc')).value;
    if (desc) {
      return desc;
    }

    return this._wechatShareConfig.defaults.desc;
  }

  private get shareImgUrl() {
    const img = (<HTMLInputElement>document.getElementById('seed-share-imgUrl')).value;
    // console.log(img);
    if (img) {
      return img;
    }

    const imgList = document.querySelectorAll('img');
   // console.log(imgList);
    for (let i = 1; imgList[i]; i++) {
      const {src, width} = imgList[i];
      if ((src.startsWith('http://') || src.startsWith('https://')) && width > 200) {
       // console.log(src)
       // console.log(width)
        return src;
      }
    }

    return this._wechatShareConfig.defaults.imgSrc;
  }



  public onMenuShareAppMessage(shareData: WechatShareInterface) {
    const config = this._wechatShareConfig;
    wx.onMenuShareAppMessage({
      title: shareData.title, // 分享标题
      desc: shareData.desc, // 分享描述
      link: shareData.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: shareData.imgUrl, // 分享图标
      type: '', // 分享类型,music、video或link，不填默认为link
      dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    });
    return this;
  }

  public onMenuShareTimeline(shareData: WechatShareInterface) {
    const config = this._wechatShareConfig;
    wx.onMenuShareTimeline({
      title: shareData.title, // 分享标题
      desc: shareData.desc, // 分享描述
      link: shareData.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: shareData.imgUrl, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    });
    return this;
  }

  public onMenuShareQQ(shareData: WechatShareInterface) {
    const config = this._wechatShareConfig;
    wx.onMenuShareQQ({
      title: shareData.title, // 分享标题
      desc: shareData.desc, // 分享描述
      link: shareData.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: shareData.imgUrl, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    });
    return this;
  }

  public onMenuShareQZone(shareData: WechatShareInterface) {
    const config = this._wechatShareConfig;
    wx.onMenuShareQZone({
      title: shareData.title || config.defaults.title, // 分享标题
      desc: shareData.desc || config.defaults.desc, // 分享描述
      link: shareData.link || location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: shareData.imgUrl || config.defaults.imgSrc, // 分享图标
      success: function () {
        // 用户确认分享后执行的回调函数
      },
      cancel: function () {
        // 用户取消分享后执行的回调函数
      }
    });

    return this;
  }

  public onMenuShareAll() {
    const shareData = this.fetchShareData();
    // console.log(shareData)
    setTimeout(() => {
      this.onMenuShareAppMessage(shareData)
        .onMenuShareTimeline(shareData)
        .onMenuShareQQ(shareData)
        .onMenuShareQZone(shareData);
    }, 1000);
  }

}
